package org.example.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    //签名随意写，但复杂，安全 性越高
    public static final String SING = "@521";

    /**
     * 生成token字符串的方法
     * 生成token
     *
     * @param map
     * @return
     */
    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        //设置token有效时间
        instance.add(Calendar.SECOND, 100);

        //创建token
        JWTCreator.Builder builder = JWT.create();

        //payload


        for (Map.Entry<String, String> entry : map.entrySet()) {
            builder.withClaim(entry.getKey(), entry.getValue());
        }

        //指定令牌的过期时间设置进入

        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));//签名使用什么加密

        return token;
    }

    /*** 验证token合法性 */
    public static boolean verifier(String token) {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /*** 获取token信息 */
    public static boolean getTokenInfo(String token) {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING))
                    .build().verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }


    }

    /*** 获取token信息 */
    public static String getTokenNo(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);

            return jwt.getClaim("mNo").asString();

        } catch (Exception e) {
            return null;
        }


    }
}
